﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;

namespace ConsoleApplication1.Asynchronous 
{
    public class HttpAsynchronous
    {
        //通知一个或多个正在等待的线程已发生事件。
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        public static void Main()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.vancl.com");
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            //开始异步操作
            //开始对用来写入数据的System.IO.Stream 对象的异步请求。
           request.BeginGetRequestStream(new AsyncCallback(ReadCallback) , request);
            //维持主线程继续直到异步操作完成。
            allDone.WaitOne();
            //获取响应
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //获取响应流
            Stream streamResponse = response.GetResponseStream();
            //读取响应流
            StreamReader streamRead = new StreamReader(streamResponse);
            //读取响应流
            string responseString = streamRead.ReadToEnd();
            Console.WriteLine(responseString);
            streamResponse.Close();
            streamResponse.Dispose();
            streamRead.Close();
            streamRead.Dispose();
            response.Close();
            Console.ReadKey();
        } 
 
        private static void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            //结束请求操作
            //结束对用于写入数据的System.IO.Stream 对象的异步请求。
            Stream postStream = request.EndGetRequestStream(asynchronousResult);
            //Console.WriteLine("输入要被POST的数据:");
           // string postData = Console.ReadLine();
           // //将字符串转化为字节数组
           byte[]byteArray = Encoding.UTF8.GetBytes("");
           // //向请求流中写入字节
           postStream.Write(byteArray , 0 ,0);
           postStream.Close();
           postStream.Dispose();
            allDone.Set();
        }

    }
}
